package com.lebang.medicalInquiry.utils;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.sdk.service.dysmsapi20170525.AsyncClient;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsResponse;
import com.google.gson.Gson;
import darabonba.core.client.ClientOverrideConfiguration;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;


import java.net.URLEncoder;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;


/**
 * @author : tony
 * @Date: 2018-11-06 12:02
 * @Description: 短信发送工具类
 */
@Slf4j
public class SendSmsUtil {
    //todo 相关参数暂时有此提供，最好有配置信息提供相关参数
    public static final String NEW_JUHE_LEBANG_SMS_URL = "http://v.juhe.cn/sms/send?mobile=%s&tpl_id=%s&tpl_value=%s&key=dc352ed5126683c0d4a1f5ec69638d17";

    private static final String MUNBER_CODE = "error_code";


    /**
     * 用户注册时发送短信验证码
     *
     * @param phone 用户手机号
     * @param code  用户的验证码
     * @return
     */
    public static boolean sendRegisterSms(String phone, String code) {
        try {
            String codeFor = String.format("#code#=%s", code);
            String url = String.format(NEW_JUHE_LEBANG_SMS_URL, phone, "252058", URLEncoder.encode(codeFor, "utf-8"));
            OkHttpClient instance = OkhttpClientUtils.getInstance();
            Response execute = instance.newCall(new Request.Builder().url(url).get().build()).execute();
            ResponseBody body = execute.body();
            assert body != null;
            String string = body.string();
            return analysisResult(string);


        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    private static boolean analysisResult(String result) {
        try {
            if (!TextUtil.isEmpty(result)) {
                JSONObject data = JSON.parseObject(result);
                if (data.containsKey(MUNBER_CODE) && data.getInteger(MUNBER_CODE) == 0) {
                    return true;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 阿里云短信发送
     *
     * @param phone
     * @param code
     * @returnaliyun:
     */
    public static boolean alySms(String phone, String signName, String templateCode, String code, String accessKeyId, String accessKeySecret) {
        StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
                // Please ensure that the environment variables ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET are set.
                .accessKeyId(accessKeyId)
                .accessKeySecret(accessKeySecret)
                //.securityToken(System.getenv("ALIBABA_CLOUD_SECURITY_TOKEN")) // use STS token
                .build());

        // Configure the Client
        AsyncClient client = AsyncClient.builder()
                //.httpClient(httpClient) // Use the configured HttpClient, otherwise use the default HttpClient (Apache HttpClient)
                .credentialsProvider(provider)
                //.serviceConfiguration(Configuration.create()) // Service-level configuration
                // Client-level configuration rewrite, can set Endpoint, Http request parameters, etc.
                .overrideConfiguration(
                        ClientOverrideConfiguration.create()
                                // Endpoint 请参考 https://api.aliyun.com/product/Dysmsapi
                                .setEndpointOverride("dysmsapi.aliyuncs.com")
                        //.setConnectTimeout(Duration.ofSeconds(30))
                )
                .build();

        // Parameter settings for API request
        SendSmsRequest sendSmsRequest = SendSmsRequest.builder()
                .phoneNumbers(phone).signName(signName).templateCode(templateCode).templateParam(code)
                // Request-level configuration rewrite, can set Http request parameters, etc.
                // .requestConfiguration(RequestConfiguration.create().setHttpHeaders(new HttpHeaders()))
                .build();

        // Asynchronously get the return value of the API request
        CompletableFuture<SendSmsResponse> response = client.sendSms(sendSmsRequest);
        // Synchronously get the return value of the API request
        SendSmsResponse resp = null;
        try {
            resp = response.get();
            String resultCode = resp.getBody().getCode();
            if ("OK".equals(resultCode)) {
                return true;
            }
            log.error("阿里云短信发送失败:{}", resp.getBody());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public static void main(String[] args) {
//        alySms("13358371215","{'code':'123456'}");
    }
}
